package main

import (
	"code.google.com/p/go.net/websocket"
	"flag"
	"fmt"
	"net/http"
	"text/template"
	"app/data"
)

// sendRecvServer echoes back text messages sent from client
// using websocket.Message.
func sendRecvServer(ws *websocket.Conn) {
	fmt.Printf("sendRecvServer %#v\n", ws)
	for {
		var buf string
		// Receive receives a text message from client, since buf is string.
		err := websocket.Message.Receive(ws, &buf)
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Printf("recv:%q\n", buf)
		// Send sends a text message to client, since buf is string.
		err = websocket.Message.Send(ws, buf)
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Printf("send:%q\n", buf)
	}
	fmt.Println("sendRecvServer finished")
}

var homeTempl = template.Must(template.ParseFiles("web/index.html"))

func homeHandler(c http.ResponseWriter, req *http.Request) {
	homeTempl.Execute(c, req.Host)
}

func main() {
	var m data.MyData
	m.Name = "Alvaro"
	flag.Parse()
	http.Handle("/sendRecvText", websocket.Handler(sendRecvServer))
	http.HandleFunc("/", homeHandler)
	http.Handle("/static/", http.StripPrefix("/static",
	  http.FileServer(http.Dir("/home/alem/workspace/gowebsockets/web"))))
	
	err := http.ListenAndServe(":23456", nil)
	if err != nil {
		panic("ListenANdServe: " + err.Error())
	}
}
